package com.liang.blog.security.interceptor;

import com.liang.blog.model.constant.CacheConstants;
import com.liang.blog.model.constant.SecurityConstants;
import com.liang.blog.redis.service.RedisService;
import com.liang.blog.security.jwt.AuthContextHolder;
import com.liang.blog.security.jwt.JwtHelper;
import com.liang.blog.security.service.TokenService;
import com.liang.blog.security.utils.BlogSecurityUtil;
import com.liang.blog.vo.user.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author：YanWenLiang
 * @Date:2023-08-23-22:08
 */
@Component
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;

    /**
     * 用户刷新令牌缓存及保存用户信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        BlogSecurityUtil.setUserId(AuthContextHolder.getUserId(request).toString());
        BlogSecurityUtil.setUserKey(AuthContextHolder.getUserKey(request));
        BlogSecurityUtil.setAccount(AuthContextHolder.getUserAccount(request));
        System.out.println(AuthContextHolder.getUserKey(request));
        System.out.println(AuthContextHolder.getUserId(request).toString());

        String token = AuthContextHolder.getToken(request);
        if (!StringUtils.isEmpty(token)){
            // 获取请求头中的token,并解析token中对应的用户唯一标识
            String userKey = JwtHelper.getUserKey(token);
            LoginUserVo loginUserVo = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + userKey);
            // 判断当前缓存中是否有用户信息,有则进行过期时间检验
            if (loginUserVo != null){
                tokenService.verifyToken(loginUserVo);
                BlogSecurityUtil.set(SecurityConstants.LOGIN_USER, loginUserVo);
            }
        }
        return true;
    }

}
